#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
from __future__ import print_function

from flask import render_template, \
     redirect, url_for

from .. import db
from . import Nao
from . import forms
from . import main


#================= 设置 ===============

@main.route('/set', methods=['GET', 'POST'])
def set():
    #flash(session)
    page_title = u"设定"
    urls = [
        {
            "url": url_for('.new_nao'),
            "text": u"添加Nao"
        },
        {
            "url": url_for('.edit_nao'),
            "text": u"编辑Nao"
        },
        {
            "url": url_for('.delete_nao'),
            "text": u"删除Nao"
        }
    ]
    texts = []
    for name in Nao.get_names():
        nao = Nao.get_by_name(name)
        texts.append("NAO: %s" % name)
        texts.append("IP: %s" % nao.IP)
        texts.append("PORT: %d" % nao.PORT)
    return render_template('index.html',page_title=page_title,urls=urls,texts=texts)

# 向数据库添加一个Nao
@main.route('/set/new_nao', methods=['GET', 'POST'])
def new_nao():
    form = forms.NewNaoForm(port=9559)
    if form.validate_on_submit():
        name = form.nao_name.data
        ip = form.ip.data
        port = form.port.data
        nao = Nao.get_by_name(name)
        if nao is None:
            nao = Nao(name,ip,port)
        else:
            nao.IP=ip
            nao.PORT=port
        db.session.add(nao)
        db.session.commit()
        return redirect(url_for('.set'))
    return render_template('form.html',name=u"向数据库添加一个Nao",form=form)

# 修改数据库中的Nao参数
@main.route('/set/edit_nao', methods=['GET', 'POST'])
def edit_nao():
    form = forms.EditNaoForm(port=9559)
    form.nao_name.choices=zip(Nao.get_names(), Nao.get_names())
    if form.validate_on_submit():
        name = form.nao_name.data
        ip = form.ip.data
        port = form.port.data
        nao = Nao.get_by_name(name)
        assert isinstance(nao,Nao)
        nao.IP=ip
        nao.PORT=port
        db.session.add(nao)
        db.session.commit()
        return redirect(url_for('.set'))
    return render_template('form.html',name=u"修改数据库中的Nao参数",form=form)

@main.route('/set/delete_nao', methods=['GET', 'POST'])
def delete_nao():
    form = forms.SelectNaoForm()
    form.nao_name.choices=zip(Nao.get_names(),Nao.get_names())
    if form.validate_on_submit():
        name = form.nao_name.data
        nao = Nao.get_by_name(name)
        assert isinstance(nao,Nao)
        nao.delete()
        db.session.delete(nao)
        db.session.commit()
        return redirect(url_for('.set'))
    return render_template('form.html',name=u"删除数据库中的Nao",form=form)